package com.cskaoyan.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pjr
 * @version 1.0.0
 * @description TODO
 * @date 2022/6/17 20:02
 */
@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    OrderConverter orderConverter;


    /**
     * 查询所有的订单
     * @param request
     * @return
     */
    @Override
    public OrderListResponse orderList(OrderListRequest request) {
        // 开启分页
        PageHelper.startPage(request.getPage(),request.getSize());
        // 订单信息 + 订单商品信息orderItemDto数组 + 订单运输信息orderShippingDto
        OrderListResponse response = new OrderListResponse();
        // 订单详情信息表
        List<OrderDetailInfo> orderDetailList = new ArrayList<>();
        try {
            // 参数校验
            request.requestCheck();

            // 查询出该用户的所有订单信息
            Example example = new Example(Order.class);
            example.createCriteria().andEqualTo("userId", request.getUserId());
            List<Order> orders = orderMapper.selectByExample(example);
            // 每个订单再查询商品信息和运输信息构成订单详情信息
            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
                // 根据订单id查询运输信息，并用converter转换为前端需要的对象
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                orderDetailInfo.setOrderShippingDto(orderConverter.shipping2dto(orderShipping));
                // 根据订单id查询商品信息，并用converter转换为前端需要的对象
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
                orderDetailInfo.setOrderItemDto(orderConverter.item2dto(orderItems));
                // 将每个订单详情添加到订单详情信息表中
                orderDetailList.add(orderDetailInfo);
            }
        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        PageInfo pageInfo = new PageInfo(orderDetailList);
        response.setDetailInfoList(orderDetailList);
        response.setTotal(pageInfo.getTotal());
        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override
    public OrderDetailResponse orderDetail(OrderDetailRequest request, HttpServletRequest servletRequest) {
        //todo 这个userId要怎么拿到?

        String userInfo = (String) servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long userId = Long.parseLong(object.get("uid").toString());

        OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
        try {
            System.out.println(request.getOrderId());
            request.requestCheck();
            String orderId = request.getOrderId();
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            // 转换为DTO
            List<OrderItemDto> orderItemDtos = orderConverter.orderItemList2dto(orderItems);
            orderDetailResponse.setGoodsList(orderItemDtos);
            // 查三表 得到需要的数据set进response
            OrderDetailUnion orderDetailUnion = orderMapper.getDetailUnion(userId,orderId);

            // 有点问题, 前端返回地址应该是xx省-xx市格式  也许要改?
            orderDetailResponse.setStreetName(orderDetailUnion.getStreetName());
            orderDetailResponse.setTel(orderDetailUnion.getTel());
            orderDetailResponse.setOrderStatus(orderDetailUnion.getOrderStatus());
            orderDetailResponse.setOrderTotal(orderDetailUnion.getOrderTotal());
            orderDetailResponse.setUserId(orderDetailUnion.getUserId());
            orderDetailResponse.setUserName(orderDetailUnion.getUserName());

            // 成功执行
            orderDetailResponse.setCode(OrderRetCode.SUCCESS.getCode());
            orderDetailResponse.setMsg(OrderRetCode.SUCCESS.getMessage());

            return orderDetailResponse;

        }catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailResponse, e);
        }
        return null;
    }
}
